package com.jinlejia.erp.ui.message;

import android.os.Bundle;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;

import com.alibaba.fastjson.JSONObject;
import com.jinlejia.erp.R;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.databinding.ActivityMessageDetailsBinding;
import com.jinlejia.erp.ui.common.AllReadMessageDialog;
import com.jinlejia.erp.ui.common.ProgressDialog;
import com.jinlejia.erp.utils.DataFilter;
import com.zhy.http.okhttp.OkHttpUtils;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;

/**
 * 消息详情（activity）
 */

public class MessageDetailsActivity extends AppCompatActivity {

    // 填充到ViewPager中的Fragment
    private List<Fragment> mFragments;
    //Tab选项卡的文字
    private String mTitleArray[] = {"全部消息（0）", "未读消息（0）", "收藏消息（0）"};
    private String allCount = "";
    private String unReadCount = "";
    private String collectCount = "";

    private InnerViewPagerAdapter viewPagerAdapter;
    private JSONObject jsonObject = new JSONObject();
    private AllReadMessageDialog dialog;
    private ProgressDialog progressDialog;

    private ActivityMessageDetailsBinding binding;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_message_details);

        binding.backBtn.setOnClickListener(this::onClick);
        binding.allRead.setOnClickListener(this::onClick);

        EventBus.getDefault().register(this);
        initView();
    }

    /**
     * 初始化视图
     */
    private void initView() {
        progressDialog = new ProgressDialog(this,"请稍等...");
        dialog = new AllReadMessageDialog(this);
        binding.title.setText(getIntent().getStringExtra("title"));

        mFragments = new ArrayList<>();
        mFragments.add(0, AllMessageFragment.newInstance(getIntent().getStringExtra("serviceType"),getIntent().getStringExtra("time")));       //全部消息
        mFragments.add(1, UnreadMessageFragment.newInstance(getIntent().getStringExtra("serviceType"),getIntent().getStringExtra("time")));    //未读消息
        mFragments.add(2, FavoritesMessageFragment.newInstance(getIntent().getStringExtra("serviceType"),getIntent().getStringExtra("time"))); //收藏消息


        viewPagerAdapter = new InnerViewPagerAdapter(this.getSupportFragmentManager(), mTitleArray, mFragments);
        binding.viewPager.setAdapter(viewPagerAdapter);
        binding.viewPager.setOffscreenPageLimit(3);

        // 设置Tablayout的Tab显示ViewPager的适配器中的getPageTitle函数获取到的标题
        binding.idTableLayout.setTabsFromPagerAdapter(viewPagerAdapter);
        binding.idTableLayout.post(() -> {
            // 将TabLayout和ViewPager进行关联，让两者联动起来
            binding.idTableLayout.setupWithViewPager(binding.viewPager);
        });

    }


    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back_btn:
                finish();
                break;
            case R.id.all_read:
                dialog.show();
                dialog.setConfirmListener(() -> {
                    jsonObject.put("serviceType", getIntent().getStringExtra("serviceType"));
                    jsonObject.put("type", getIntent().getStringExtra("time"));
                    AllRead();
                });
                break;
        }
    }

    /**
     * 全部已读
     */
    private void AllRead() {
        progressDialog.show();
        OkHttpUtils
                .postString()
                .url(ApiConfig.MESSAGE_ALL_READ)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (DataFilter.filter(MessageDetailsActivity.this, response, null)) {
                            EventBus.getDefault().post("refresh","TAG_REFRESHINFO_TAG");
                        }
                    }
                });
    }

    @Subscriber(tag = "TAG_MESSAGE_TAG")
    private void numChange(Map<String, String> map) {
        switch (map.get("state")) {
            case "allMessage":
                allCount = "（" + map.get("allCount") + "）";
                mTitleArray[0] = "全部消息".concat(allCount);
            case "unReadCount":
                unReadCount = "（" + map.get("unReadCount") + "）";
                mTitleArray[1] = "未读消息".concat(unReadCount);
            case "collectMessage":
                collectCount = "（" + map.get("collectCount") + "）";
                mTitleArray[2] = "收藏消息".concat(collectCount);
                break;
        }
        viewPagerAdapter.notifyDataSetChanged();
    }

    @Override
    public void onDestroy() {
        if (null != progressDialog && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    private static class InnerViewPagerAdapter  extends FragmentStatePagerAdapter {
        private String[] mTitles;
        private List<Fragment> mFragments;

        public InnerViewPagerAdapter(FragmentManager fm, String[] mTitles, List<Fragment> mFragments) {
            super(fm);
            this.mTitles = mTitles;
            this.mFragments = mFragments;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTitles[position];
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }

    }
}
